package com.atguigu.flink.datastream.transform;

import org.apache.flink.streaming.api.datastream.ConnectedStreams;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author WEIYUNHUI
 * @date 2023/6/14 9:33
 *
 *  connect合流 :
 *        可以支持两条不同类型的流进行connect ，
 *        实际上两条流没有真正的合并到一起，在内部处理的过程中，还是区分对待，
 *        但是最终要将两条流的类型进行统一， 真正意义上变成一条流。
 *
 *
 *
 */
public class Flink10_ConnectStream {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<Integer> ds1 = env.fromElements(1, 2, 3, 4, 5);

        //DataStreamSource<Integer> ds2 = env.fromElements(6, 7, 8, 9, 10);

        DataStreamSource<String> ds3 = env.fromElements("a", "b", "c", "d", "e");

        //connect
        ConnectedStreams<Integer, String> connectedStreams = ds1.connect(ds3);
        SingleOutputStreamOperator<String> processDs = connectedStreams.process(
                new CoProcessFunction<Integer, String, String>() {
                    /**
                     * 处理第一条流的数据
                     */
                    @Override
                    public void processElement1(Integer value, CoProcessFunction<Integer, String, String>.Context ctx, Collector<String> out) throws Exception {
                        out.collect(value.toString());
                    }

                    /**
                     * 处理第二条流的数据
                     */
                    @Override
                    public void processElement2(String value, CoProcessFunction<Integer, String, String>.Context ctx, Collector<String> out) throws Exception {
                        out.collect(value.toUpperCase());
                    }
                }
        );

        processDs.print();


        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
